package org.company.management.ui;

import java.util.List;

import org.company.management.controller.EmployeeGroupJpaController;
import org.company.management.controller.EmployeeJpaController;
import org.company.management.controller.UiController;
import org.company.management.entity.Employee;
import org.company.management.entity.EmployeeGroup;
import org.company.management.utilities.CustomMessageBox;
import org.company.management.utilities.Strings;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.nebula.widgets.gallery.DefaultGalleryGroupRenderer;
import org.eclipse.nebula.widgets.gallery.DefaultGalleryItemRenderer;
import org.eclipse.nebula.widgets.gallery.Gallery;
import org.eclipse.nebula.widgets.gallery.GalleryItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.wb.swt.ResourceManager;
import org.eclipse.wb.swt.layout.grouplayout.GroupLayout;

/**
 * @author Paner
 *
 */
public class EmployeeGalleryEditor extends EditorPart implements SelectionListener, MouseListener {

	public final static String ID = Strings.employeeGalleryEditorId;
	
	private Gallery _gallery;
	private Button _addButton;
	private Button _deleteButton;
	private Button _updateButton;
	
	private MenuItem _openItem;
	private MenuItem _updateItem;
	private MenuItem _deleteItem;
	
	/*
	 * Constructor, sets editor`s image
	 */
	public EmployeeGalleryEditor() {
		setTitleImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.galleryPicture16x16));

	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void doSaveAs() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);

	}

	@Override
	public boolean isDirty() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isSaveAsAllowed() {
		// TODO Auto-generated method stub
		return false;
	}

	/* 
	 * Create gallery parts
	 */
	@Override
	public void createPartControl(Composite parent) {
		createControls(parent);
		createLayout(parent);
		fillEditor();

	}
	
	/*
	 * Creates widgets
	 */
	@SuppressWarnings("deprecation")
	private void createControls(Composite parent)
	{
		
		_gallery = new Gallery(parent, SWT.BORDER | SWT.V_SCROLL);
		_gallery.addMouseListener(this);
		_gallery.setVertical(true);
		_gallery.setGroupRenderer(new DefaultGalleryGroupRenderer());
		_gallery.setItemRenderer(new DefaultGalleryItemRenderer());
		
		Menu popupMenu = new Menu(_gallery);
		
		_openItem = new MenuItem(popupMenu, SWT.NONE);
		_openItem.setText(Strings.open);
		_openItem.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.openUserPicture16x16));
		_openItem.addSelectionListener(this);
		
		_updateItem = new MenuItem(popupMenu, SWT.NONE);
		_updateItem.setText(Strings.update);
		_updateItem.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.editUserPicture16x16));
		_updateItem.addSelectionListener(this);
		
		_deleteItem = new MenuItem(popupMenu, SWT.NONE);
		_deleteItem.setText(Strings.delete);
		_deleteItem.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.deleteUserPicture16x16));
		_deleteItem.addSelectionListener(this);
		
		_gallery.setMenu(popupMenu);
		
		_addButton = new Button(parent, SWT.NONE);
		_addButton.setToolTipText(Strings.addUserTooltip);
		_addButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.addUserPicture32x32));
		_addButton.addSelectionListener(this);
		
		_updateButton = new Button(parent, SWT.NONE);
		_updateButton.setToolTipText(Strings.editUserTooltip);
		_updateButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.editUserPicture32x32));
		_updateButton.addSelectionListener(this);
		
		_deleteButton = new Button(parent, SWT.NONE);
		_deleteButton.setToolTipText(Strings.deleteUserTooltip);
		_deleteButton.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.deleteUserPicture32x32));
		_deleteButton.addSelectionListener(this);
		
	}
	
	/*
	 * Creates Layout
	 */
	private void createLayout(Composite parent) 
	{
		GroupLayout gl_parent = new GroupLayout(parent);
		gl_parent.setHorizontalGroup(
			gl_parent.createParallelGroup(GroupLayout.LEADING)
				.add(gl_parent.createSequentialGroup()
					.addContainerGap()
					.add(gl_parent.createParallelGroup(GroupLayout.LEADING)
						.add(_gallery, GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)
						.add(gl_parent.createSequentialGroup()
							.add(_addButton)
							.add(6)
							.add(_updateButton)
							.add(6)
							.add(_deleteButton)))
					.addContainerGap())
		);
		gl_parent.setVerticalGroup(
			gl_parent.createParallelGroup(GroupLayout.LEADING)
				.add(gl_parent.createSequentialGroup()
					.addContainerGap()
					.add(gl_parent.createParallelGroup(GroupLayout.LEADING)
						.add(_addButton)
						.add(_updateButton)
						.add(_deleteButton))
					.add(7)
					.add(_gallery, GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
					.addContainerGap())
		);
		parent.setLayout(gl_parent);
		
	}
	
	/*
	 * Fills the components of the editor
	 */
	private void fillEditor()
	{
	
		EmployeeGroupJpaController employeeGroupDao = new EmployeeGroupJpaController();
		List<EmployeeGroup> employeeGroups = employeeGroupDao.findEmployeeGroupEntities();
		

		for(EmployeeGroup employeeGroup : employeeGroups)
		{
			//Creates gallery items for existing groups
			GalleryItem galleryItem = new GalleryItem(_gallery, SWT.NONE);
			galleryItem.setText(employeeGroup.getName());
			galleryItem.setExpanded(true);
		}
		
		//Creates empty gallery item 
		GalleryItem emptyItem = new GalleryItem(_gallery, SWT.NONE);
		emptyItem.setText(Strings.none);
		emptyItem.setExpanded(true);

		EmployeeJpaController employeeDao = new EmployeeJpaController();
		List<Employee> employees = employeeDao.findEmployeeEntities();
		
		for(Employee employee : employees)
		{
			try
			{
				GalleryItem[] groupItems = _gallery.getItems();
				GalleryItem galleryItem_1 = null;
				
				// Place employee to specified group in gallery
				if(employee.getGroupid() == null)
				{
					galleryItem_1 = new GalleryItem(emptyItem, SWT.NONE);
				}
				else
				{
					for(GalleryItem item : groupItems)
					{
						if(item.getText().equals(employee.getGroupid().getName()))
						{
							galleryItem_1 = new GalleryItem(item, SWT.NONE);					
							break;
						}
					}
				}
				galleryItem_1.setData(employee);
				galleryItem_1.setText(employee.getName());
				
				//Set employee picture
				if(employee.getPicture() == null || employee.getPicture().isEmpty())
				{
					galleryItem_1.setImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.defaultPhoto));
				}
				else
				{
					Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
					Image employeeImage = new Image(shell.getDisplay(), employee.getPicture());
					galleryItem_1.setImage(employeeImage);
				}
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
		
	}

	@Override
	public void widgetSelected(SelectionEvent e) 
	{
		Object selectedWidget = e.getSource();
		
		if (selectedWidget == _addButton)
		{
			try
			{
				UiController.showEditor(Strings.gallery, AddEmployeeEditor.ID);
			}
			catch(Exception ex)
			{
				
			}
		}
		else if (selectedWidget == _deleteButton)
		{
			try
			{
				
				GalleryItem[] selectedEmployee = _gallery.getSelection();
				int selectedItemsCount = selectedEmployee.length;
				
				//delete employee from db
				if(selectedItemsCount != 0)
				{
					if(CustomMessageBox.showYesNoMessageBox(Strings.invalidInputHeader, Strings.confirmSelection))
					{
						Employee employee = (Employee)selectedEmployee[0].getData();
						employee.setEmployeeScheduleList(null);
						
						EmployeeJpaController employeeDao = new EmployeeJpaController();
						employeeDao.destroy(employee.getId());
						
						_gallery.remove(selectedEmployee[0]);
					}
				}	
			}
			catch(Exception ex)
			{
				//ex.printStackTrace();
			}	
		}
		else if (selectedWidget == _updateButton)
		{
			try
			{
				GalleryItem[] selectedEmployee = _gallery.getSelection();
				Employee employee = (Employee)selectedEmployee[0].getData();
				UiController.showEditor(employee, UpdateEmployeeEditor.ID);
			}
			catch(Exception ex)
			{
				//
			}
		}
		
		// Opens editor using popup menu
		else if (selectedWidget == _openItem)
		{
			try
    		{
	    		GalleryItem[] selectedEmployee = _gallery.getSelection();
				Employee employee = (Employee)selectedEmployee[0].getData();
	    		UiController.showEditor(employee, EmployeeCardEditor.ID);
    		}
    		catch(Exception ex)
    		{
    			//
    		}
		}
		
		// Opens editor using popup menu
		else if (selectedWidget == _updateItem)
		{
			try
			{
				GalleryItem[] selectedEmployee = _gallery.getSelection();
				Employee employee = (Employee)selectedEmployee[0].getData();
				UiController.showEditor(employee, UpdateEmployeeEditor.ID);
			}
			catch(Exception ex)
			{
				//
			}
		}
		
		// Deletes employee using popup menu
		else if (selectedWidget == _deleteItem)
		{
			try
			{
				if(CustomMessageBox.showYesNoMessageBox(Strings.invalidInputHeader, Strings.confirmSelection))
				{
					GalleryItem[] selectedEmployee = _gallery.getSelection();
					Employee employee = (Employee)selectedEmployee[0].getData();
					
					//delete employee from db
					EmployeeJpaController employeeDao = new EmployeeJpaController();
					employeeDao.destroy(employee.getId());
					
					_gallery.remove(selectedEmployee[0]);
				}
					
			}
			catch(Exception ex)
			{
				//ex.printStackTrace();
			}
		}
	}

	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	/*
	 * Double click mouse event
	 */
	@Override
	public void mouseDoubleClick(MouseEvent e)
	{
		try
		{
			GalleryItem[] selectedEmployee = _gallery.getSelection();
			Employee employee = (Employee)selectedEmployee[0].getData();
    		UiController.showEditor(employee, EmployeeCardEditor.ID);
		}
		catch(Exception ex)
		{
			//ex.printStackTrace();
		}
		
	}

	@Override
	public void mouseDown(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseUp(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	

	@Override
	public void setFocus() {
	// TODO Auto-generated method stub

	}

}
